<?php
/**
 * Created by PhpStorm
 * User: 陈志洪
 * Date: 2020/1/21
 * Time: 20:12
 */

namespace app\api\controller;

use app\common\controller\Api;
use Endroid\QrCode\QrCode;
use think\Request;

class Base extends Api
{
    protected $noNeedLogin = [];

    public function __construct()
    {
        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }

    // 重构操作成功返回的数据
    protected function success($msg = '', $data = null, $code = 200, $type = 'json', array $header = [])
    {
        // TODO: Change the autogenerated stub
        parent::success($msg, $data, $code, $type, $header);
    }

    // 重构操作失败返回的数据
    protected function error($msg = '', $data = null, $code = 400, $type = 'json', array $header = [])
    {
        // TODO: Change the autogenerated stub
        parent::error($msg, $data, $code, $type, $header);
    }

    // 重构验证数据
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        // TODO: Change the autogenerated stub
        $result = parent::validate($data, $validate, $message, $batch, $callback);

        if ($result !== true) {
            $this->error('error', $result, 400);
        }

        return true;
    }

    // 根据逗号分割，丢进数组内
    public static function getArrayByExplode($string)
    {
        return explode(',', $string);
    }

    // 删除最后一个字符
    public static function delEndString($string)
    {
        return substr($string, 0, strlen($string) - 1);
    }

    /**
     * 截取富文本字符
     * @param $string string 文本内容
     * @param $num int 截取长度
     * @return string
     */
    public static function stringToText($string, $num)
    {
        if ($string) {
            //把一些预定义的 HTML 实体转换为字符
            $html_string = htmlspecialchars_decode($string);
            //将空格替换成空
            $content = str_replace(" ", "", $html_string);
            //函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
            $contents = strip_tags($content);
            //返回字符串中的前$num字符串长度的字符
            return mb_strlen($contents, 'utf-8') > $num ?
                mb_substr($contents, 0, $num, "utf-8") . '...' :
                mb_substr($contents, 0, $num, "utf-8");
        } else {
            return $string;
        }
    }

    // 校验参数是否是正整数
    public static function checkIsIntNumberByArray($array)
    {
        $match = "/^[1-9][0-9]*$/";

        foreach ($array as $value) {
            if (!preg_match($match, $value)) {
                return false;
            }
        }

        return true;
    }

    // 生成订单号
    public static function makeOrderNo()
    {
        return intval(date('Y')) // 获取当前年份
            . strtoupper(dechex(date('m'))) // 获取月份 十进制转16进制 转为大写字符串
            . date('d') // 日
            . substr(time(), -5) // 时间戳生成
            . substr(microtime(), 2, 5) // 时间戳的微秒数字
            . sprintf('%02d', rand(0, 99)); // 从 0-99 之间取一个随机数
    }

    // get 请求数据
    public static function getCurl($url, &$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // 不做证书校验，部署在Linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, strpos(PHP_OS, "Linux") ? true : false);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }

    // 生成二维码
    public static function getCode($data)
    {
        // 创建基本二维码
        $qrCode = new QrCode($data);
        $qrCode->setSize(300); // 尺寸
        $file_name = md5(microtime(true) . time()); // 文件名称
        if (!file_exists(ROOT_PATH . 'public/qrcode')) {
            mkdir(ROOT_PATH . 'public/qrcode', 0700);
        }

        $qrCode->writeFile(ROOT_PATH . 'public/qrcode' . DS . $file_name . '.png'); // 保存二维码图片
        return '/qrcode/' . $file_name . '.png';
    }

    // 生成核销编号
    public static function cancelNumber($productId)
    {
        return 'xh' .
            time() //时间戳
            . sprintf('%02d', rand(0000, 9999))// 从 0-99 之间取一个随机数
            . $productId;

    }

    /**
     * 加密
     * @param $txt
     * @param string $key
     * @return string
     * @since: 2020/8/15
     * @author: Lin Zhengyu
     */
    public function lock_url($txt, $key = 'password')
    {
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }
        return urlencode($ch . $tmp);
    }


    /**
     * 解密
     * @param $txt
     * @param string $key
     * @return false|string
     * @since: 2020/8/15
     * @author: Lin Zhengyu
     */
    public function unlock_url($txt, $key = 'password')
    {
        $txt = urldecode($txt);
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) $j += 64;
            $tmp .= $chars[$j];
        }
        return base64_decode($tmp);
    }




}
